import { FC, useState } from 'react';
import { Layout, Menu } from 'antd';
import type { MenuProps } from 'antd';
import { useNavigate, useLocation } from 'react-router-dom';
import { useSelector } from 'react-redux';
import {
  HomeOutlined,
  RobotOutlined,
  FileTextOutlined,
  LineChartOutlined,
  BookOutlined,
  ExperimentOutlined,
  ShareAltOutlined,
} from '@ant-design/icons';
import { RootState } from '../store';
import styles from './SideMenu.module.css';

const { Sider } = Layout;

const SideMenu: FC = () => {
  const navigate = useNavigate();
  const location = useLocation();
  const visibleMenus = useSelector((state: RootState) => state.menu.visibleMenus);

  // 获取当前路径的一级路径
  const getRootPath = (path: string) => {
    const parts = path.split('/');
    return parts.length > 1 ? `/${parts[1]}` : path;
  };

  // 设置默认展开的菜单
  const defaultOpenKeys = ['report', '/knowledge'];
  const [openKeys, setOpenKeys] = useState<string[]>(defaultOpenKeys);

  // 保持菜单展开状态
  const handleOpenChange = (keys: string[]) => {
    const rootPath = getRootPath(location.pathname);
    const latestOpenKey = keys.find(key => !openKeys.includes(key));

    if (latestOpenKey) {
      setOpenKeys(keys);
    } else {
      setOpenKeys(rootPath === '/knowledge' ? ['/knowledge'] : []);
    }
  };

  const menuItems = [
    visibleMenus.home && {
      key: '/home',
      icon: <HomeOutlined />,
      label: '首页'
    },
    visibleMenus.chat && {
      key: '/chat',
      icon: <RobotOutlined />,
      label: '产业问答'
    },
    visibleMenus.trend && {
      key: '/trend',
      icon: <LineChartOutlined />,
      label: '趋势分析'
    },
    visibleMenus.report && {
      key: 'report',
      icon: <FileTextOutlined />,
      label: '智能报告',
      children: [
        {
          key: '/report/industry',
          label: '产业报告'
        },
        {
          key: '/report',
          label: '报告管理'
        },
        {
          key: '/report/phase-summary',
          label: '阶段总结'
        }
      ]
    },
    visibleMenus.knowledge && {
      key: '/knowledge',
      icon: <BookOutlined />,
      label: '知识库管理'
    },
    visibleMenus['tech-insight'] && {
      key: '/tech-insight',
      icon: <ExperimentOutlined />,
      label: '技术洞察',
    },
    {
      key: '/graph-builder',
      icon: <ShareAltOutlined />,
      label: '图谱构建'
    },
  ].filter(Boolean) as MenuProps['items'];

  return (
    <Sider width={200} className={styles.sider}>
      <Menu
        mode="inline"
        selectedKeys={[location.pathname]}
        openKeys={openKeys}
        onOpenChange={handleOpenChange}
        items={menuItems}
        onClick={({ key }) => navigate(key)}
      />
    </Sider>
  );
};

export default SideMenu;